<?php
// +----------------------------------------------------------------------
// | makePHP 
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://makephp.org All rights reserved.
// +----------------------------------------------------------------------
// | Licensed BSD.(http://www.make.org/BSD-license.txt)
// +----------------------------------------------------------------------
// | Author: 叁石(sanshi) <sanshi0815@tom.com>
// | Author: 白家昌<baijc2004cn@126.com>
// +----------------------------------------------------------------------

/**
 * 后台顶层类
 * @name    TheAdmin
 * @see
 * @version	1.0.0 (Tue Nov 04 15:54:48 CST 2008)
 * @author	sanshi
 */

//加载配置文件
require_once(dirname(dirname(__FILE__))."/common/config.inc.php");
header("content-type:text/html; charset=utf-8");

class TheAdmin
{
	public $smarty;
	private $menus_file_name ;
	private $permission_file_name;
	private $auto_load = true;
	private $permission_arr = array();
	public $userRequest;
	public  $admin_user_id;
   /**
	* 构造函数
	* @return void
	* @access public
	*/
	public function __construct()
	{
		$this->TheAdmin();
	}
	function TheAdmin()
	{
		$this->userRequest = Factory::getBaseClass('UserRequest');
		//设置加载菜单的文件
		$this->menus_file_name = CACHE_PATH.'admin/menus.data';
		$this->permission_file_name = CACHE_PATH.'admin/permission.data';

		//如果文件过期，则不启动自动加载
		$overTime = 0;//过期时间
		if(time()-@fileatime($this->permission_file_name)>$overTime) $this->auto_load = true;

		$this->smarty = Factory::getSmarty();
		//$this->smarty->template_dir = TPL_PATH."admin/";
		//$this->smarty->compile_dir = COM_PATH."admin/";
		//皮肤模板
		$this->smarty->template_dir = TPL_PATH.SKIN_FILE;
		$this->smarty->compile_dir = COM_PATH.SKIN_FILE;
		//显示用户名和组名
		$this->smarty->assign('css_path',CSS_PATH );
		$this->smarty->assign('js_path', JS_PATH);
		$this->smarty->assign('pic_path', PIC_PATH);
		$this->smarty->assign('cache_path', CACHE_PATH);
		$this->smarty->assign('upload_file_path', UPLOAD_URL);
		$this->smarty->assign('host_cache_path', HOST_CACHE_PATH);
		#$this->smarty->assign('upload_max',VIDEO_MAX_SIZE);
		#$this->smarty->assign('up_load_path',HOST_UPLOAD_PATH);
		#$this->smarty->assign('up_transn_path',TRANSN_UPLOAD);
		$this->smarty->assign('admin_user_id',$this->get_login_id());
		$this->smarty->assign('main_menus',$this->get_main_menus());
		$this->smarty->assign('admin_info',get_admin_info());//取得管理员用户数组
		$this->smarty->assign('price_type_arr',get_price_type_arr());//币种
		//print_r(get_project_arr());
		$this->smarty->assign('project_arr',get_project_arr());//项目数组
		$this->smarty->assign('smc_type',get_mc_type());  //获得设备类别
		$this->smarty->register_function('create_popedom',"smarty_create_popedom");
		$this->smarty->register_function('get_username',"smarty_get_username");
		
		$this->smarty->register_function('get_pj','smarty_get_pj');
		$this->smarty->register_function('cut_str',"smarty_cut_str");
		$this->smarty->register_function('format_money','smarty_format_money');
		$this->smarty->register_function('format_c',smarty_format_c);
		$this->smarty->register_function('get_first_time','smarty_get_first_time');
	}
	function get_main_menus()
	{
		$user_popedom = $this->get_user_popedom();
		$menus_arr = $this->get_menus();
		$temp = array();
		for ($i=0;$i<count($menus_arr);$i++)
		{
			if($this->get_user_popedom_by_class_name($menus_arr[$i]['url']))
			{
				$temp[]= "<a href=?c=".$menus_arr[$i]['url'].">".$menus_arr[$i]['title']."</a>";
			}
		}
		if(!IS_ROOT)
		{
			$temp[] = "<a href=".HOST_PATH."login.php?act=login_out>退出</a>";
			$temp[] = "<a href=".ADMIN_HOST_PATH.">返回首页</a>";
		}
		return $temp;
	}
	function check_login()
	{
		$admin_user_id = $this->userRequest->get('admin_user_id');
		if(empty($admin_user_id) && !IS_ROOT) {
			$this->smarty->display('admin_login.tpl');
			exit();
			//alertMsg(-2002,HOST_PATH.'admin/login.php');
		}
		return $admin_user_id;
	}
	function get_login_id()
	{
		$admin_user_id = $this->userRequest->get('admin_user_id');
		return $admin_user_id ? $admin_user_id : 0;
	}
	function get_user_popedom()
	{
		return unserialize($this->userRequest->get('admin_user_permission'));
	}
	function get_user_menus()
	{
		//取得用户权限
		$user_popedom = $this->get_user_popedom();
		$menus_arr = $this->get_menus();
		$temp = array();
		for ($i=0;$i<count($menus_arr);$i++)
		{
			if($this->get_user_popedom_by_class_name($menus_arr[$i]['url'],$user_popedom))
				$temp[] = array('url'=>"?c={$menus_arr[$i]['url']}",'title'=>$menus_arr[$i]['title']);
		}
		if(!IS_ROOT) $temp[]=array('url'=>HOST_PATH."/login.php?act=login_out",'title'=>"退出");
		return $temp;
	}
	function make_menus()
	{
		//过滤不进入菜单的类名
		$filter_class = array("index","ctrl_prpedom");
		$temp = array();
		$io = Factory::getBaseClass('FileIO');
		$dir_name = ADMIN_PATH.'include/';
		//echo $dir_name;
		$dir_file_arr = $io->getDirFile($dir_name);
		//print_r($dir_file_arr);
		//exit();
		$permission_arr = array();
		foreach ($dir_file_arr['file'] as $k=>$v)
		{
			$name_arr = explode('.',$v);
			include_once($dir_name.$v);
			$object_name = $name_arr[0];
			if(in_array($object_name,$filter_class)) continue;
			$new_object = new $object_name();
			$class_arr = $new_object->show_p();
			//echo $object_name."<br/>";
			//continue;
			$temp[] = array('url'=>$class_arr['class_name'][0],'title'=>$class_arr['class_name'][1]);

			$permission_arr[$object_name]['title'] = $class_arr['class_name'][1];
			//echo $permission_arr[$object_name]['title']."<br/>";

			foreach ($class_arr['class_method'] as $k=>$v)
			{
				if($v[2]!=0)
					$permission_arr[$object_name]['method'][] = array($v[1],$v[2]);
			}

			unset($new_object);
			unset($class_arr);
		}
		$io->writeFile($this->menus_file_name,serialize($temp));
		$io->writeFile($this->permission_file_name,serialize($permission_arr));
		return  array($temp,$permission_arr);
	}
	function get_permission_arr()
	{
		if(is_file($this->permission_file_name) && !$this->auto_load)
		{
			$io = Factory::getBaseClass('FileIO');
			return unserialize($io->getFileContent($this->permission_file_name));
		}else {
			$temp = $this->make_menus();
			return $temp[1];
		}
	}
	function get_menus()
	{
		if(is_file($this->menus_file_name) && !$this->auto_load)
		{
			$io = Factory::getBaseClass('FileIO');
			return unserialize($io->getFileContent($this->menus_file_name));
		}else {
			$temp = $this->make_menus();
			return $temp[0];
		}
	}
	function get_user_popedom_by_class_name($class_name)
	{
		$user_popedom_arr = $this->get_user_popedom();
		if(IS_ROOT) return $class_name;
		//判断用户有无权限操作这个类
		return isset($user_popedom_arr[$class_name]) ? $user_popedom_arr[$class_name] : 0;
	}
	//后台权限控制层，使用类
	/**
 	* 检测用户类
 	* @name   user_popedom
 	* @param  string	$class_name 	需要执行的类名
 	* @param  string	$action 	    需要执行的方法名
 	* @return bool 	$return  有权限执行，返回true
 	* @access public
 	* @see
 	* @version	1.0.0 (Tue Nov 04 09:04:48 CST 2008)
 	* @author	sanshi
 	*/
	function user_popedom($class_name,$action)
	{
		$return = false;
		$user_p = $this->get_user_popedom_by_class_name($class_name);
		//实例将要进行操作的类
		$new_class = Factory::getAdminClass($class_name);
		//取得该类的方法权限数组
		$class_p_arr = $new_class->show_p();
		if($class_name=="index")
		{			
			$new_class->set();
			$new_class->$action();
			return true;
		}
		//判断要执行的方法是否在类中
		if(isset($class_p_arr['class_method'][$action][2]))
		{
			//取得该方法的权值
			$class_p = $class_p_arr['class_method'][$action][2];
			if(parse_power($user_p,$class_p) || IS_ROOT)
			{
				$new_class->set();
			    $new_class->$action();
			    $return = true;
			}else{
				if($action==DEFANT_METHOD)
				{
					$new_class->set();
					$new_class->_display();
					$return = true;
				}
			}
		}
		
		//echo time() .$class_name."->".$action .($return ? "--有权限" : '--无权限')."</br>";exit;
		unset($new_class);
		//return true;
		return $return;
	}

	/**
	 * (功能描述) 上传文件
	 *
	 * @param 
	 * @return
	 */
	public function upload_file_xls($savePath='', $fields='fileName', $allowFile = array('xls'))
	{
		$result['state'] = 0; //0 失败 1 成功
		$result['msg'] = '上传失败'; //提示

		if(empty($fields) || empty($savePath)) {
			return $result;
		}

		$base_upload = Factory::getBaseClass("UploadOne");
		$base_upload->allowFile = $allowFile;//允许上传格式
		$base_upload->uploadFileFize = 5000*1024; //上传大小限制5M
		$init = $base_upload->init($fields);
		if(0 > $init) {
			$result['msg'] = '只允许上传.xls格式文档，上传大小限制少于5M.';
			return $result;
		}
		//$ext = $base_upload->get_ext_name(); //扩展名
		$filePath = $base_upload->exec_upload($savePath);
		if(empty($filePath)) {
			return $result;
		}
		//获取上传后文件名
		$fileName = $base_upload->get_pathinfo($filePath);
		$result['state'] = 1;
		$result['msg'] = $fileName;
		return $result;
	}

}
function admin_log($admin_u_id,$action,$log_info,$log_type)
{
	$temp['admin_log_id'] = "";
	$temp['admin_user_id'] = $admin_u_id;
	$temp['admin_log_action'] = $action;
	$temp['admin_log_time'] = time();
	$temp['admin_log_type'] = $log_type;
	$temp['ip_address'] = getUserIP();
	$temp['admin_log_inof'] = $log_info;
	if(defined('ADMIN_USE_LOG4J') && ADMIN_USE_LOG4J)
	{
		include_once(LOG4J_PATH."Logger.php");
		Logger::configure(ADMIN_LOG4J_CONFIG);
		$logger = Logger::getLogger('admin');
		unset($temp['admin_log_id']);
		//$temp['admin_log_inof'] = serialize($temp['admin_log_inof']);
		$log_msg = implode(' ',$temp);
		$logger->debug($log_msg);
	}else{
		$db = Factory::getDB('admin_log');
		$db->insert_admin_log($temp);
		//$error_sql = end($db->getDebugMsg());
		//echo $error_sql;
	}
}

//$permission_arr,$admin_permission_arr,$post_name = "admin_group_permission";
function smarty_create_popedom($params)
{
	extract($params);
	$temp = "";
	foreach ($permission_arr AS $k=>$v)
	{
		$temp.="<strong>{$v['title']}</strong><br>";
		foreach ($v['method'] as $key=>$value)
		{
				$temp.="&nbsp;&nbsp;&nbsp;&nbsp;";
				$temp.="<input type=checkbox name='{$post_name}[{$k}][]' value={$value[1]}";
				$temp.=(isset($admin_permission_arr[$k])&&parse_power($admin_permission_arr[$k],$value[1])) ? " checked " : "";
				$temp.=">{$value[0]}";
		}
		$temp.="<br>";
	}
	return $temp;
}
/**
 * 文件上传
 *
 * @param unknown_type $data
 * @param unknown_type $file_name
 * @return unknown
 */
function upload_file($data,$filed_name,$file_name='',$c='')
{
	//判断上传是否错误
	if ($data["{$filed_name}"]["error"] > 0) {
		alertMsg('-2007');
	}
	$Upload_db = Factory::getBaseClass('UploadOne');
	$Upload_db->init("{$filed_name}");
	$up_path_temp = md5($c);
	$up_path = UPLOAD_PATH.substr($up_path_temp,0,2).PATH.substr($up_path_temp,3,5).PATH;
	$temp = $Upload_db->exec_upload($up_path,$file_name);
	if (intval($temp) < 0) {
		alertMsg($temp);
	}else{
		return $temp;
	}
}
/**
 * 取得后台管理员用户数组（管理员ID=>名称）
 *
 * @return unknown
 */
function get_admin_info()
{
	$admin_user_db = Factory::getDB('admin_user');
	$temp = $admin_user_db->get_user_info();
	return $temp ;
}
/**
 * 取得项目数组
 *
 */
function get_project_arr()
{
	$zy_project_db = Factory::getDB('zy_project');
	$temp = $zy_project_db->get_project_arr();
	return $temp;
}

/**
*
*
*/
function smarty_get_username($params)
{
	extract($params);
	$db = Factory::getDB('admin_user');
	$arr = $db->getOne($user_id);
	return $arr['admin_user_name'];
}
/**
 * 截取
 *
 * @param unknown_type $params
 * @return unknown
 */
function smarty_cut_str($params)
{
	extract($params);
	return cut_str($str,$sublen,$start=0);
}

function smarty_get_pj($params){
	extract($params);
	$db = Factory::getDB('zy_sell_reply');
	$arr = $db->getOne($id);
	$p_db = Factory::getDB('zy_project');
	$temp = $p_db->getOne($arr['project_id']);
	return $temp['project_name'];
}

function smarty_format_money( $params )//格式化金额,精确到两位小数点
{
	extract($params);
    if ( $STR == "" )
    {
        return "";
    }
    if ( $STR == ".00" )
    {
        return "0.00";
    }
    $TOK = strtok( $STR, "." );
    if ( strcmp( $STR, $TOK ) == "0" )
    {
        $STR .= ".00";
    }
    else
    {
        $TOK = strtok( "." );
        $I = 1;
        for ( ; $I <= 2 - strlen( $TOK ); ++$I )
        {
            $STR .= "0";
        }
    }
    if ( substr( $STR, 0, 1 ) == "." )
    {
        $STR = "0".$STR;
    }
    return $STR;
}

function smarty_get_first_time($params)
{
	extract($params);
	$db = Factory::getDB('zy_allocation_log');
	$where = "comp_no='{$comp_no}'";
	$arr = $db->getAll($where);
	if(isset($arr[0])){
		return date('Y-m-d',$arr[0]['start_time']);
	}else{
		return '';
	}
}
/**
 * 格式化类型
 *
 * @param unknown_type $params
 * @return unknown
 */
function smarty_format_c($params)
{
	extract($params);
	$temp = md5($c);
	return substr($temp,0,2).PATH.substr($temp,3,5).PATH;
}


function get_user_group($uid)
{
	$db = Factory::getDB('admin_user');
	$u_arr = $db->getOne($uid);
	$g_db = Factory::getDB('admin_group');
	$g_arr = $g_db->getOne($u_arr['admin_group_id']);
	return array('user'=>$u_arr['admin_user_name'],'group'=>$g_arr['admin_group_title']);
}
/**
 * 获得调拨单号
 *
 */
function getallno()
	{
		//$sql = "";
		$mc_allocation_db = Factory::getDB('zy_mc_allocation');
		$where = 1;
		$arr = $mc_allocation_db->getAll($where,'allocation_no',1,0,'SUBSTR(  `allocation_no` , -3, 3 ) temp_no');
		$temp_no = isset($arr[0]) ? $arr[0]['temp_no'] : '001';
		$d   =   sprintf( "%03d ",   $temp_no+1);
		return 'CSDB-'.date('Y').'-'.$d;
	}
?>